const { OpenAI } = require("openai");
const { Stream } = require("openai/core/streaming");
const { apiKey, systemContent } = require("@/config/default").aliyun;
const Validate = require("@/validate")
const tools = require("@/config/tools")

const openai = new OpenAI(
    {
        // 若没有配置环境变量，请用百炼API Key将下行替换为：apiKey: "sk-xxx",
        apiKey,
        baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
    }
);

class ChatController{
    // 调用流式输出
    async chatMessage(ctx){
        const {chatMessage} = ctx.request.body
        // 校验
        await Validate.isArrayCheck(chatMessage, 'chatMessage字段不能为空', "chatMessage");
        let messages = [
            { role: "system", content: systemContent },
            // { role: "user", content: "你是谁？" },//用户提问
            // { role: "assistant", content: "你是谁？" },//大模型回复
            // { role: "user", content: "你是谁？" },//用户提问
            // { role: "assistant", content: "你是谁？" },//大模型回复
            // { role: "user", content: "你是谁？" },//用户提问
            // { role: "assistant", content: "你是谁？" },//大模型回复
            ...chatMessage
        ]
        const completion = await openai.chat.completions.create({
        model: "qwen-max",  //模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
        messages,
        stream: true,
        // @ts-ignore
        tools

        });
        
        // console.log(JSON.stringify(completion))
        // 迭代
        for await (const chunk of completion) {
            // console.log(JSON.stringify(chunk));
            const str = JSON.stringify(chunk);
            const obj = JSON.parse(str);
            // 判断是否可以调用函数/工具
            console.log(str);
            const choices = obj.choices[0].delta
            if(choices.content === null && choices.tool_calls) {
                console.log('用工具调用');
                if(messages[messages.length - 1].role !== 'assistant') {
                    messages.push({ "role": "user", "content": "你是谁？" })
                }
            }
        }
    }
}

module.exports = new ChatController();